'''
二叉树右视图：

先进行层序遍历，把每层最后一个元素的值加入结果链表。
'''
from collections import deque

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def rightSideView(root: TreeNode):
    if not root:
        return []
    
    result = []
    queue = deque([root])
    
    while queue:
        level_size = len(queue)
        for i in range(level_size):
            node = queue.popleft()
            # 如果是当前层的最后一个节点，加入结果
            if i == level_size - 1:
                result.append(node.val)
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
    
    return result
def test_rightSideView():
    # 测试示例 1
    root = TreeNode(1)
    root.left = TreeNode(2)
    root.right = TreeNode(3)
    root.left.right = TreeNode(5)
    root.right.right = TreeNode(4)
    assert rightSideView(root) == [1, 3, 4], "测试示例 1 失败"
    
    # 测试示例 2: 只有右子树的树
    root = TreeNode(1)
    root.right = TreeNode(3)
    assert rightSideView(root) == [1, 3], "测试示例 2 失败"
    
    # 测试示例 3: 空树
    root = None
    assert rightSideView(root) == [], "测试示例 3 失败"
    
    # 测试示例 4: 完全二叉树
    root = TreeNode(1)
    root.left = TreeNode(2)
    root.right = TreeNode(3)
    root.left.left = TreeNode(4)
    root.left.right = TreeNode(5)
    root.right.left = TreeNode(6)
    root.right.right = TreeNode(7)
    assert rightSideView(root) == [1, 3, 7], "测试示例 4 失败"
    
    print("所有测试用例通过！")

# 运行测试
test_rightSideView()